from flask import Flask, request, jsonify, render_template, Response
import urllib.parse
import requests
import json
import json
app = Flask(__name__)
@app.route('/')
def index():
    # 使用render_template返回index.html页面
    return render_template('index.html')
headers = {
    'accept': 'application/json',
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin':'*'
}

def generate_stream(data):
    # 这里定义你的生成器逻辑，该逻辑应该向客户端发送数据块
    for line in data.iter_content(None, decode_unicode=True):
        json_data = json.loads(line.split('data: ')[-1].rstrip())
        if 'docs' in json_data.keys():
            dict1 = {}
            for k,vs in json_data.items():
                for v in vs:
                    # print('v: ',v.replace('\n',''))
                    file_name = v.split('(')[0].replace('[','').replace(']','')
                    v0 = v.split('=')[0]
                    v1 = v.split('=')[-1].split(')')[-1]
                    v1 = urllib.parse.unquote(v1)
                    k = k.replace('\n','')
                    v0 = v0.replace('\n','')
                    v1 = v1.replace('\n',', ')
                    # print(f"json_data:{file_name} : {v1}\n\n")
                    dict1[file_name] = v1
            yield f"data_file: {json.dumps(dict1, ensure_ascii=False)}\n\n".encode('utf-8')
        else:
            yield f"data: {json.dumps(json_data, ensure_ascii=False)}\n\n".encode('utf-8')
        # yield json.dumps(line).encode('utf-8')
        # yield line

@app.route('/send_message', methods=['POST'])
def send_message():
    data = request.get_json()
    print(f"data:{data}")
    response = requests.post('http://0.0.0.0:7861/chat/knowledge_base_chat',json=data, stream=True, headers=headers)
    return Response(generate_stream(response), content_type='text/event-stream')

if __name__ == '__main__':
    app.run(host="0.0.0.0",port=5000,debug=True)
    # app.run(host="192.168.6.143",port=5000,debug=True)

'''
data_file: {
    "出处 1 云鹰平台服务系统接口协议V1.8.4.pdf": ", trousecolorScore, Float, 裤子颜色得分, trousetype, , ", 
    "出处 2 云鹰平台服务系统接口协议V1.8.4.pdf": " , , 名称, 1, 蓝牌, 2, 白牌, 3, 黄牌单层, 4, 黄牌双层, 5, 绿牌, 6, 黄绿牌, 7, 黑牌, 8, 其他, 4.2.3 车辆颜色字典, 数值, 名称, 1, 蓝色, 2, 绿色, 3, 黑色, 4, 紫色, 5, , ", 
    "出处 3 云鹰平台服务系统接口协议V1.8.4.pdf": " , , 绿色, 3, 黑色, 4, 紫色, 5, 红色, 云鹰平台系统接口标准, 28, 6, 黄色, 7, 白色, 8, 灰色, 9, 棕色, 10, 粉色, 11, 其他, 4.3 硬件故障字典, 4.3.1 故障字典, 数值, 名称, 1, CPU 温度过高, 2, , "
    } 
'''

